<?php
/**
 * Permission Service
 * User: zng
 * Date: 2019/11/4
 * Time: 14:34
 */
namespace app\admin\service;

use app\exceptions\OrdinaryException;
use app\admin\model\admin\{
    MenuCategory,Menus as MenusModel
};

Class Menus {

    /**
     * 首页列表
     * @param array $get 筛选条件
     * @author zx
     * @date 2019-12-06
     * @return \think\Paginator
     */
    public function indexPaginate( array $get=[] )
    {
        $map = [];
        if ( get($get, 'name') ) {
            $map[] = ['name', 'LIKE', $get['name'].'%'];
        }
        if ( get($get, 'status') === 0 || get($get, 'status') === '0' || get($get, 'status') == 1 ) {
            $map[] = ['status', '=', $get['status']];
        }
        if ( get($get, 'start_sort_num') !== NULL && get($get, 'start_sort_num') !== '' ) {
            $map[] = ['sort_num', '>=', $get['start_sort_num']];
        }
        if ( get($get, 'end_sort_num') !== NULL && get($get, 'end_sort_num') !== '' ) {
            $map[] = ['sort_num', '<=', $get['end_sort_num']];
        }
        if ( get($get, 'start_level') ) {
            $map[] = ['level', '>=', $get['start_level']];
        }
        if ( get($get, 'end_level') ) {
            $map[] = ['level', '<=', $get['end_level']];
        }
        if ( get($get, 'start_create_at') ) {
            $map[] = ['create_at', '>=', $get['start_create_at'].' 00:00:00'];
        }
        if ( get($get, 'end_create_at') ) {
            $map[] = ['create_at', '<=', $get['end_create_at'].' 23:59:59'];
        }
        $pageSize = get($get,'pageSize')>0?$get['pageSize']:20;
        return MenusModel::where($map)
            ->order('id', 'desc')
            ->paginate($pageSize);
    }

    /**
     * 状态更改
     * @author zx
     * @date 2019-11-14
     * @return \think\response
     */
    public function status(MenusModel $model)
    {
        $status = (int)(!$model->status);
        $model->status = $status;
        $update = $model->save();
        if ( $update ) {
            return success(['status'=>$status]);
        }
        return failed('更新失败');
    }

    /**
     * 新增\编辑分组信息
     * @param array $data 数据包
     * @author zx
     * @date 2019-11-14
     * @throws OrdinaryException
     * @return boolean|integer
     */
    public function create(array $data)
    {
        $menu = MenusModel::create($data, ['name','path','sort_num','status','level','icon']);
        return $menu->isEmpty()?false:$menu->id;
    }

    /**
     * 批量删除
     * @param mixed $data
     * @author zx
     * @date 2019-11-15
     * @throws OrdinaryException
     * @return boolean
     */
    public function destory( $data )
    {
        return MenusModel::destroy(function($query)use($data){
            $where = ['id', '=', $data];
            if ( is_array($data) ) {
                $where = ['id', 'in', $data];
            }
            $query->where([
                $where
            ]);
        });
    }

    /**
     * 判断是否唯一
     * @param array $data
     * @author zx
     * @date 2019-12-06
     * @return boolean
     */
    public function only(array $data)
    {
        $map = [];
        $id = get($data, 'id', 0);
        if ( get($data, 'name') ) {
            $map[] = ['name', '=', $data['name']];
        }
        if ( $id <= 0 ) {
            $count = MenusModel::where($map)->count();
            if ( $count > 0 ) {
                return false;
            }
        } else {
            $idResult = MenusModel::where($map)->column('id');
            foreach ( $idResult as $_id ) {
                if ( $_id != $id ) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 关联权限分组
     * @param int $mid
     * @param array $cid 权限分组id
     * @throws OrdinaryException
     * @return true
     */
    public function relation(int $mid, array $cid)
    {
        if ( empty($cid) ) {
            return true;
        }
        if ( empty($mid) ) {
            throw new OrdinaryException('参数错误');
        }
        $model = new MenuCategory();
        $model->startTrans();
        if ( $model->where('menu_id', $mid)->delete() === false ) {
            $model->rollback();
            throw new OrdinaryException('删除原有关联失败');
        }
        $menuCategory = [];
        foreach ( $cid as $item) {
            $menuCategory[] = [ 'menu_id' => $mid, 'category_id' => $item ];
        }
        if ( $model->saveAll( $menuCategory ) === false ) {
            $model->rollback();
            throw new OrdinaryException('分配权限分组失败');
        }
        $model->commit();
        return true;
    }

    /**
     * 根据菜单id获取分类列表
     * @param int $mid 菜单id
     * @return array
     */
    public function getCategory(int $mid)
    {
        return MenuCategory::where('menu_id', $mid)->column('category_id');
    }

    /**
     * 菜单管理编辑
     * @param int $id
     * @param array $data
     */
    public function save(int $id, array $data)
    {
        return (new MenusModel())
            ->allowField(['name','path','sort_num','status','level','icon'])
            ->isUpdate()->save($data, $id);
    }

    /**
     * 获取菜单树
     * @param array $userInfo 登录信息
     */
    public function getMenus( array $inCategory=[] )
    {
        if ( $inCategory === [] ) {
            return MenusModel::field('id,name,path,level,icon')
                ->where('status', 0)->order('sort_num', 'asc')->select();
        }
        return MenusModel::field('menus.id,menus.name,menus.path,menus.level,menus.icon')
            ->alias('menus')
            ->leftJoin('menu_category', 'menus.id = menu_category.menu_id')
            ->where('menu_category.category_id', 'IN', $inCategory)
            ->order('menus.sort_num', 'asc')->group('menus.id')->select();
    }


}